package hn.cch.spring.boot.filter;

import hn.cch.spring.boot.annotation.ApiAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class HandlerInterceptorImpl implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(HandlerInterceptorImpl.class);

    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) {
        logger.info("preHandle");

        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();

        }
        return true;
    }


    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle");

    }



    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        logger.info("afterCompletion");

        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(ApiAnnotation.class) || clazz.isAnnotationPresent(ApiAnnotation.class)) {
                final int statusCode = response.getStatus();
                logger.info("Method: {}", method.getName());
                if (statusCode != HttpStatus.OK.value()) {
                    logger.error("HttpStatus:{}, Exception:", statusCode, exception);
                }
            }
        }
    }

}
